/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.systemView;

/**
 * 说明：
 * 数据库备份与还原
 * @Author：黄盛强
 * @Date：2012-04-28
 */
import java.awt.FileDialog;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.ruidom.Com.Transform.DBDump.XMLDataExport;
import com.ruidom.Com.Transform.DBDump.XMLDataLoader;
import com.ruidom.util.PrintWriter;
import com.ruipengkj.bean.TProductCatalog;
import com.ruipengkj.bean.TRole;
import com.ruipengkj.bean.TRoleRight;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.jdbc.ConnectionNetWork;
import com.ruipengkj.service.TConfigService;
import com.ruipengkj.service.TProductCatalogService;
import com.ruipengkj.service.TRoleRightService;
import com.ruipengkj.service.TRoleService;
import com.ruipengkj.view.base.BasePanel;

public class SystemBackupReduction extends BasePanel {

	private JButton backupButton;// 备份
	private JButton reductionButton;// 还原
	private JButton deleteButton;//删除

	private static final long serialVersionUID = 1L;

	private String username;//数据库用户名
	private String password;//数据库密码
	
	private TProductCatalogService tProductCatalogService = BuildSpringApplication.getInstance().getTProductCatalogServiceImpl();
	private TRoleService tRoleService;
	private TRoleRightService tRoleRightService;
	
	private TConfigService tConfigService = BuildSpringApplication.getInstance().getTConfigServiceImpl();
	
	public SystemBackupReduction() {
		tRoleService=BuildSpringApplication.getInstance().getTRoleServiceImpl();
		tRoleRightService=BuildSpringApplication.getInstance().getTRoleRightServiceImpl();
		this.init();
	}

	private void init() {
		backupButton = new JButton("数据库备份");
		reductionButton = new JButton("数据库还原");
		deleteButton= new JButton("删除数据库数据");//,SwingUtil.getOpenSwingImage("database_remove.png")
//		delAllButton.setHorizontalTextPosition(SwingConstants.CENTER);
//		delAllButton.setVerticalTextPosition(SwingConstants.BOTTOM);
		backupButton.addActionListener(this);
		reductionButton.addActionListener(this);
		deleteButton.addActionListener(this);
		this.add(backupButton);
		this.add(reductionButton);
		this.add(deleteButton);
	}

	// 选择本地文件
	private String selectFile(String title, boolean save) {
		FileDialog fileChooser = null;
		if (save)
			fileChooser = new FileDialog(new JFrame(), title, FileDialog.SAVE);
		else
			fileChooser = new FileDialog(new JFrame(), title);
		fileChooser.setVisible(true);
		if (fileChooser.getDirectory()!= null && fileChooser.getFile() != null) {
			return fileChooser.getDirectory() + fileChooser.getFile();
		}
		return null;
	}
	
	// 处理带空格的路径
	private String DisplayPath(String path) {
		if (path == null || path.length() == 0)
			return null;
		String newPath = "";// 记录新字符串
		String s = "";// \ 分割的字符串
		boolean bNull = false;// 是否存在空字符
		for (int i = 0; i < path.length(); ++i) {
			if (path.charAt(i) == ' ') {
				bNull = true;
			}
			if (path.charAt(i) == '\\') {
				if (bNull) {
					newPath += "\"" + s + "\"\\";
					bNull = false;
				} else {
					newPath += s + "\\";
				}
				s = "";
			} else {
				s += path.charAt(i);
			}
		}
		return newPath + s;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		//使用FileDialog不可过滤
//		username=InitContext.getinstance().LoadDataBaseData().getProperty("pool.username");
//		password=InitContext.getinstance().LoadDataBaseData().getProperty("pool.password");
//		if(username==null||password==null||username.equals("")){
//			JOptionPane.showMessageDialog(null, "数据库连接失败，请检查连接参数是否配置正确");
//			return;
//		}
		if (e.getSource() == backupButton) {
//			List<TConfig> tConfigList = null;
//			try {
//				tConfigList = tConfigService.findService(null);
//			} catch (Exception e2) {
//				e2.printStackTrace();
//			}
//			if (tConfigList == null || tConfigList.size() == 0) {
//				Util.showMessageDialog("请先在系统设置中设置MySql安装目录！");
//				return;
//			}
//			String path = selectFile("保存文件", true);
//			try {
//				if (path != null && path.length() != 0) {
//					//C:\\\"Program Files\"\\MySQL\\\"MySQL Server 5.0\"\\bin\\
//					path = "cmd /c "+DisplayPath(tConfigList.get(0).getSqlPath()+"\\bin")+"\\mysqldump -u "+username+" -p"+password+" --database ruipengkj > " + DisplayPath(path) + ".sql";
////					System.out.println(path);
//					Runtime.getRuntime().exec(path).waitFor();
//					JOptionPane.showMessageDialog(null, "备份成功！");
//					return;
//				}
//			} catch (IOException e1) {
//				e1.printStackTrace();
//			} catch (InterruptedException e1) {
//				e1.printStackTrace();
//			}
//			JOptionPane.showMessageDialog(null, "备份失败！");
			PrintWriter pw = null;
			Connection conn = null;
			try {
				pw = new PrintWriter(new java.io.PrintWriter(new FileWriter(
						"test.xml")));
				conn = new ConnectionNetWork().getConnection();// DBHelper.GetInstance().getConnection();
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("show tables;");
				List<String> tables = new ArrayList<String>();
				while (rs.next()) {
					String str = rs.getString(1);
					if (!str.contains("view")) {
						tables.add(str);
					}
				}
				new XMLDataExport().export(pw, conn, tables);
				conn.close();
				pw.close();
				Util.showMessageDialog("备份成功！");
			} catch (Exception e2) {
				e2.printStackTrace();
				Util.showMessageDialog("备份失败！");
			} finally {
				try {
					conn.close();
					pw.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		} else if(e.getSource()==reductionButton){
//			String path = selectFile("选择文件", false);
//			if (path != null) {
//				// 判断选择的是否是。sql结尾文件
//				if (!path.toLowerCase().endsWith(".sql"))
//					if (JOptionPane.showConfirmDialog(null,"你选择了非sql文件，有可能不能还原，确定吗？") != 0) {
//						return;
//					}
//				try {
////					System.out.println("cmd /c mysql -u "+username+" -p"+password+" --database ruipengkj < "
////									+ DisplayPath(path));
//					Runtime.getRuntime().exec(
//							"cmd /c mysql -u "+username+" -p"+password+" --database ruipengkj < "
//									+ DisplayPath(path)).waitFor();
////					System.out.println(DisplayPath(path));
//					JOptionPane.showMessageDialog(null, "还原成功！");
//					return;
//				} catch (IOException e1) {
//					e1.printStackTrace();
//				} catch (InterruptedException e1) {
//					e1.printStackTrace();
//				}
//				JOptionPane.showMessageDialog(null, "还原失败！");
//			}
			Connection conn = null;
			BufferedReader breader = null;
			try {
	            XmlPullParser xpp = null;
	            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	            factory.setNamespaceAware(true);
	            xpp = factory.newPullParser();
	            breader = new BufferedReader(new InputStreamReader(new FileInputStream("test.xml")), 1024 * 2);
	            xpp.setInput(breader);
	            conn = new ConnectionNetWork().getConnection();
	            new XMLDataLoader(null).load(conn, xpp);
	            Util.showMessageDialog("还原成功！");
	        }
	        catch (Exception e2)
	        {
	            e2.printStackTrace();
	            Util.showMessageDialog("还原失败！");
	        }finally {
	        	try {
					conn.close();
					breader.close();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
	            
	        }
		}else if(e.getSource()==deleteButton){
			//数据库删除
			ConnectionNetWork connectionNetWork = new ConnectionNetWork();
			if(JOptionPane.showConfirmDialog(null, "是否要删除数据库数据？","信息提示",JOptionPane.YES_NO_OPTION)==0){
				try {
					connectionNetWork.insert("delete from  ruipeng_tb_tpurchase");//
					connectionNetWork.insert("delete from  ruipeng_tb_TSupplier");//
					connectionNetWork.insert("delete from  ruipeng_tb_TStoreTransfer");//
					connectionNetWork.insert("delete from  ruipeng_tb_TStockInOutDetail");//
					connectionNetWork.insert("delete from  ruipeng_tb_TStockInOut");//
					connectionNetWork.insert("delete from  ruipeng_tb_TStockAlarm");//
					connectionNetWork.insert("delete from  ruipeng_tb_TStock");//
					connectionNetWork.insert("delete from  ruipeng_tb_TShopCharge");//
					connectionNetWork.insert("delete from  ruipeng_tb_TShop");//
					connectionNetWork.insert("delete from  ruipeng_tb_TSendCardRecord");//
					connectionNetWork.insert("delete from  ruipeng_tb_TScheduled");//
//					connectionNetWork.insert("delete from  ruipeng_tb_TRoleRight");
//					connectionNetWork.insert("delete from  ruipeng_tb_TRight");
					connectionNetWork.insert("delete from  ruipeng_tb_TPurchaseReturn");//
					connectionNetWork.insert("delete from  ruipeng_tb_TOutBill");//
					connectionNetWork.insert("delete from  ruipeng_tb_TOrderReturn");//
					connectionNetWork.insert("delete from  ruipeng_tb_TOrder");//
					connectionNetWork.insert("delete from  ruipeng_tb_TOpLog");//
					connectionNetWork.insert("delete from  ruipeng_tb_TMyMessage");//
					connectionNetWork.insert("delete from  ruipeng_tb_TMyCashCard");//
					connectionNetWork.insert("delete from  ruipeng_tb_TMoneyInOut");//
					connectionNetWork.insert("delete from  ruipeng_tb_TGift");//
					connectionNetWork.insert("delete from  ruipeng_tb_TFeeDetail");//
					connectionNetWork.insert("delete from  ruipeng_tb_TFee");//
					connectionNetWork.insert("delete from  ruipeng_tb_TEmployee where ruipeng_tb_TEmployee.employeeid <> 'aAAh1tkdgoqMItc'");
//					connectionNetWork.insert("delete from  ruipeng_tb_TEmployee");
					connectionNetWork.insert("delete from  ruipeng_tb_TDiscount");//
					connectionNetWork.insert("delete from  ruipeng_tb_TDept where ruipeng_tb_tdept.deptid <> 'aAAh1tkdadrxevx'");
//					connectionNetWork.insert("delete from  ruipeng_tb_TDept");
					connectionNetWork.insert("delete from  ruipeng_tb_TCommodity");//
					connectionNetWork.insert("delete from  ruipeng_tb_TConfig");//
					connectionNetWork.insert("delete from  ruipeng_tb_TUserRevisit");//
					connectionNetWork.insert("delete from  ruipeng_tb_TStore");//
					connectionNetWork.insert("delete from  ruipeng_tb_TSendInfo");//
					connectionNetWork.insert("delete from  ruipeng_tb_TCashcard");//
					connectionNetWork.insert("delete from  ruipeng_tb_TFeeType");//
					connectionNetWork.insert("delete from  ruipeng_tb_TUser");//
					connectionNetWork.insert("delete from  ruipeng_tb_TShopMemberLevel");//
					connectionNetWork.insert("delete from  ruipeng_tb_TBilldetaildes");//
					connectionNetWork.insert("delete from  ruipeng_tb_TBilldetail");//
					connectionNetWork.insert("delete from  ruipeng_tb_tsitegift");//
					connectionNetWork.insert("delete from  ruipeng_tb_TExePos");//	
					connectionNetWork.insert("delete from  ruipeng_tb_TExePosCatalog");//	
					
					//删除ruipeng_tb_TProductCatalog
					List<TProductCatalog> TProductCatalogList = tProductCatalogService.findListService(null);
					for (int i = TProductCatalogList.size() - 1; i >= 0; --i) {
						recursionDel(TProductCatalogList.get(i).getCatalogID());//进入递归 删除数据库 删除子节点
						tProductCatalogService.deleteService(TProductCatalogList.get(i).getCatalogID());//删除完所有子节点后删除父节点
					}
					
					//删除 ruipeng_tb_TRole
					List<TRole> tRoleList = tRoleService.findService(null);
					for (int i = tRoleList.size() - 1; i >= 0; --i) {
						TRole role=tRoleList.get(i);
						//删除权限
						if (!role.getRoleID().equals("aAAh1wx51fiYqLq")) {
							Set<TRoleRight> set2=role.getTRoleRights();
							if(set2!=null&&set2.size()!=0){
								Iterator<TRoleRight> it=set2.iterator();
								while(it.hasNext()){
									TRoleRight rr=it.next();
									tRoleRightService.deleteService(rr.getId());
								}
							}
							tRoleService.deleteService(role.getRoleID());
						}
					}
					
//					connectionNetWork.insert("delete from  ruipeng_tb_TRole");
//					connectionNetWork.insert("delete from  ruipeng_tb_TRole where ruipeng_tb_TRole.roleid <> 'aAAh1wx51fiYqLq'");
					JOptionPane.showMessageDialog(null, "删除成功");
					connectionNetWork.close();
				} catch (HeadlessException e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "删除失败");
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "删除失败");
				} finally {
					connectionNetWork.close();
				}
			}
		}
	}
	
	//递归删除子节点
	private void recursionDel(String parentID) {
		if (parentID == null || parentID.equals(""))
			return;
		TProductCatalog tProductCatalog = new TProductCatalog();//根据父节点查询分类
		tProductCatalog.setTProductCatalog(new TProductCatalog(parentID));
		try {
			List<TProductCatalog> tProductCatalogList = tProductCatalogService.findService(tProductCatalog);
			if (tProductCatalogList == null)
				return;
			for (int i = tProductCatalogList.size() - 1; i >= 0; --i) {
				recursionDel(tProductCatalogList.get(i).getCatalogID());//开始递归 删除
				tProductCatalogService.deleteService(tProductCatalogList.get(i).getCatalogID());//删除分类
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}
}
